<template>
  <div class="coach-student">
    <el-card class="main-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">学员列表</span>
          <div class="header-controls">
            <el-input
              v-model="searchQuery"
              placeholder="请输入学员姓名"
              style="width: 220px; margin-right: 15px;"
              clearable
              @input="debouncedSearch"
              @clear="handleSearchClear"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
        </div>
      </template>

      <!-- 学员表格 -->
      <el-table
        :data="filteredStudents"
        style="width: 100%"
        v-loading="loading"
        element-loading-text="加载中..."
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        border
      >
        <el-table-column label="序号" width="60" align="center">
          <template #default="scope">
            {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="fullname" label="学员姓名" min-width="120" />
        <el-table-column prop="enrollment_date" label="注册日期" min-width="100" />
        <el-table-column prop="phone" label="联系电话" min-width="120" />
        <el-table-column prop="license_type" label="驾照类型" min-width="100" />
        <el-table-column prop="current_level" label="学习阶段" min-width="100" />
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          background
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import requestUtil from '@/util/request.js'
import debounce from 'lodash/debounce'

// 数据相关
const students = ref([])
const allStudents = ref([]) // 存储所有学生数据用于前端过滤
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)

// 获取教练的所有学员
const fetchStudents = async () => {
  loading.value = true
  try {
    const userId = localStorage.getItem('user_id')
    if (!userId) {
      ElMessage.error('用户未登录或会话已过期')
      return
    }

    // 获取教练ID
    const coachResponse = await requestUtil.get(`/coach/msg/userId/${userId}`)
    const coachId = coachResponse.data.data.coach_id

    // 根据教练ID获取该教练相关的学员
    const response = await requestUtil.get(`/student/msg`)

    if (response.data?.status === 200) {
      // 处理数据
      const rawData = response.data.data || []
      allStudents.value = rawData
      total.value = rawData.length

      // 更新分页数据
      updatePaginatedData()
    } else {
      ElMessage.error(response.data?.message || '获取学员列表失败')
      allStudents.value = []
      students.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取学员信息失败:', error)
    ElMessage.error('获取学员信息失败: ' + (error.message || '未知错误'))
    allStudents.value = []
    students.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 使用前端过滤和分页
const filteredStudents = computed(() => {
  let filtered = allStudents.value

  // 应用搜索过滤
  if (searchQuery.value.trim()) {
    const query = searchQuery.value.trim().toLowerCase()
    filtered = filtered.filter(student =>
      (student.fullname && student.fullname.toLowerCase().includes(query)) ||
      (student.phone && student.phone.includes(query))
    )
  }

  // 更新总数量
  total.value = filtered.length

  // 应用分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filtered.slice(start, end)
})

// 更新分页数据
const updatePaginatedData = () => {
  // 触发计算属性重新计算
}

const debouncedSearch = debounce(() => {
  currentPage.value = 1 // 重置到第一页
}, 300)

// 处理搜索清除
const handleSearchClear = () => {
  searchQuery.value = ''
  currentPage.value = 1
}

// 分页相关
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page) => {
  currentPage.value = page
}

// 组件挂载时获取数据
onMounted(() => {
  fetchStudents()
})
</script>

<style scoped>
.coach-student {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 84px);
}

.main-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-controls {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-table th) {
  font-weight: 600;
}

:deep(.el-table .el-table__cell) {
  padding: 8px 0;
}
</style>
